package cn.edu.jxau.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.jxau.dao.UserDao;
import cn.edu.jxau.domain.user;
import cn.edu.jxau.service.checkMessage;

public class findPasswordServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String temp = request.getParameter("temp");
		if ("1".equals(temp)) {
			String username = request.getParameter("userName");// 获取用户名
			username = new String(username.getBytes("iso-8859-1"), "utf-8");// 若用户名是中文则对其进行转码
			String code = request.getParameter("code"); // 获取用户输入的验证码
			
			checkMessage checkMessage=new checkMessage();
			
			user user = checkMessage.checkInfo(username);
			HttpSession session = request.getSession();
			// 判断该用户名是否查出了用户信息
			if (user != null) {
				String vcode = (String) session.getAttribute("code");
				session.setAttribute("findName", username);
				if (vcode.equalsIgnoreCase(code)) {
					String mail = user.getMail(); // 从数据库中获取该用户对应的mail
					session.setAttribute("mail", mail);
					String maillocked = mail.replaceAll(mail.substring(3, 7), "****");// 对取出来的邮箱进行加密处理

					session.setAttribute("maillocked", maillocked);
					response.sendRedirect("find2.jsp");
				} else {
					request.setAttribute("cmsg", "验证码错误,请重新输入");
					request.getRequestDispatcher("find1.jsp").forward(request, response);
				}
			} else {
				request.setAttribute("umsg", "该用户名不存在");
				request.getRequestDispatcher("find1.jsp").forward(request, response);
			}
		} else if ("2".equals(temp)) {

			String vcode = request.getParameter("vcode");// 获取用户输入的验证码
			Cookie[] cookie = request.getCookies(); // 获取保存了验证码的cookie
			for (int i = 0; i < cookie.length; i++) {
				if (cookie[i].getName().equals("code")) {
					if (vcode.equals(cookie[i].getValue())) {
						response.sendRedirect("find3.jsp");
						return;
					} else {
						request.setAttribute("error", "验证码错误");
						request.getRequestDispatcher("find2.jsp").forward(request, response);
					}
				}

			}
			request.setAttribute("error", "验证码错误");
			request.getRequestDispatcher("find2.jsp").forward(request, response);
		} else if ("3".equals(temp)) {

			String pwd = request.getParameter("pwd");
			String npwd = request.getParameter("npwd");
			if (pwd.equals(npwd)) {
				UserDao userdao = new UserDao();
				HttpSession session = request.getSession();
				userdao.updata((String) session.getAttribute("findName"), pwd);
				response.sendRedirect("find4.html");
			}
		}
	}
}
